#include <filesystem> //c++17
#include <iostream>
#include <string>
#include "Mutex.hpp"
#include <ctime>

#include <sstream>
#include <fstream>
#include <memory>
#include <unistd.h>
#include<filesystem>

using namespace std;
using std::cout;
using std::endl;

namespace log
{
    // 默认路径和日志名称
    const std::string defaultpath = "./mylog/";
    const std::string defaultname = "log.txt";

    // 设置日志等级
    enum class LogLevel
    {
        DEBUG,
        INFO,
        WARNING,
        ERROR,
        FATAL
    };
    // 日志转为字符串
    std::string LogLevelToString(LogLevel level)
    {
        switch (level)
        {
        case LogLevel::DEBUG:
            return "DEBUG";
        case LogLevel::INFO:
            return "INFO";
        case LogLevel::WARNING:
            return "WARNING";
        case LogLevel::ERROR:
            return "ERROR";
        case LogLevel::FATAL:
            return "FATAL";
        default:
            return "UNKNOWN";
        }
    }

    std::string GetCurrTime()
    {
        time_t tm = time(nullptr);
        struct tm curr;
        localtime_r(&tm, &curr);
        // 这⾥如果不好看，可以考虑sprintf
        // ⽅法 1
        // std::stringstream ss;
        // ss << curr.tm_year + 1900 << "-" << curr.tm_mon << "-" <<
        // curr.tm_mday << " ";
        // << curr.tm_hour << ":" << curr.tm_min << ":" << curr.tm_sec;
        // return ss.str();
        // ⽅法 2
        char timebuffer[64];
        snprintf(timebuffer, sizeof(timebuffer), "%4d-%02d-%02d %02d : %02d : %02d",
                 curr.tm_year + 1900,
                 curr.tm_mon,
                 curr.tm_mday,
                 curr.tm_hour,
                 curr.tm_min,
                 curr.tm_sec);
        return timebuffer;
    }

    // 策略模式
    class LogStrategy
    {
    public:
        virtual ~LogStrategy() = default;
        virtual void Synclog(const std::string &message) = 0; // bu同策略下刷新方式是不同的
    };

    // 控制台日志策略就是想显示器打印
    class Console : public LogStrategy
    {
    public:
        void Synclog(const std::string &message) override
        {
            zgw::LockGuard me(_mutex);
            cout << message << endl;
        }

    private:
        zgw::Mymutex _mutex;
    };
    // 文件日志策略
    class File : public LogStrategy
    {
    public:
        std::string _logfilename;
        std::string _logpath;
        zgw::Mymutex _mutex;

    public:
        File(const std::string logpath = defaultpath, std::string logfilename = defaultname) : _logpath(logpath),
                                                                                               _logfilename(logfilename)
        {
            zgw::LockGuard mu(_mutex);

            if (std::filesystem::exists(_logpath)) // 如果路径存在，则不创建
            {
                cout << "log path already exists: " << _logpath << endl;
                return;
            }
            try
            {
                std::filesystem::create_directories(_logpath);
            }
            catch (const std::filesystem::filesystem_error &e)
            {
                cout<<"create log path failed: " << e.what() << endl;
            }
        }
        // 将日志写入文件
        void Synclog(const std::string &message) override
        {
            zgw::LockGuard mu(_mutex);
            std::string log = _logpath + _logfilename;
            std::ofstream out(log.c_str(), std::ios::app);
            if (!out.is_open())
            {
                cout << "open log file failed: " << log << endl;
                return;
            }
            out << message << "\n";
            out.close();
        }
    };

    class Logger
    {
    public:
        Logger()
        {
            _strategy = make_unique<Console>();
        }
        ~Logger()
        {
        }

        void UseConsoleStrategy()
        {
            _strategy = std::make_unique<Console>();
        }
        void UseFileStrategy()
        {
            _strategy = std::make_unique<File>();
        }
        class LogMessage
        {
        private:
            LogLevel _type;         // ⽇志等级
            std::string _curr_time; // ⽇志时间
            pid_t _pid;             // 写⼊⽇志的时间
            std::string _filename;  // 对应的⽂件名
            int _line;              // 对应的⽂件⾏号
            Logger &_logger;        // 引⽤外部logger类, ⽅便使⽤策略进⾏刷新
            std::string _loginfo;   // 完整日志消息
        public:
            LogMessage(LogLevel ty, std::string &filename, int line, Logger &logger)
                : _type(ty),
                  _curr_time(GetCurrTime()),
                  _pid(getpid()),
                  _line(line),
                  _logger(logger),
                  _filename(filename)
            {
                stringstream ssbuffer;
                ssbuffer << "[" << _curr_time << "] "
                         << "[" << LogLevelToString(_type) << "] "
                         << "[" << _pid << "] "
                         << "[" << _filename << "] "
                         << "[" << _line << "]"
                         << " - ";
                _loginfo = ssbuffer.str();
            }
            // 用模板支持任意类型参数
            template <class T>
            LogMessage &operator<<(const T &info)
            {
                std::stringstream ssbuffer;
                ssbuffer << info;
                _loginfo += ssbuffer.str();
                return *this;
            }
            // raii风格,析构时
            ~LogMessage()
            {
                if (_logger._strategy)
                {
                    _logger._strategy->Synclog(_loginfo);
                }
            }
        };

        LogMessage operator()(LogLevel type, std::string filename, int line)
        {
            return LogMessage(type, filename, line, *this);
        }

    private:
        std::unique_ptr<LogStrategy> _strategy;
    };
    Logger logger;
#define LOG(type) logger(type, __FILE__, __LINE__)
}
